package com.zlzxm.studentscreen.ui.activity;

import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.tencent.mmkv.MMKV;
import com.zlzxm.studentscreen.R;
import com.zlzxm.studentscreen.globe.Constant;
import com.zlzxm.studentscreen.net.http.RetrofitClient;
import com.zlzxm.studentscreen.net.http.RxAndroidHelp;
import com.zlzxm.studentscreen.net.http.repository.MyRepository;
import com.zlzxm.studentscreen.net.http.response.BaseResponse;
import com.zlzxm.studentscreen.net.http.response.RpBindDevice;
import com.zlzxm.studentscreen.net.http.response.RpDeviceStatus;
import com.zlzxm.studentscreen.net.http.response.RpUnBindDevice;
import com.zlzxm.studentscreen.service.CoreService;
import com.zlzxm.studentscreen.service.ServiceStart;
import com.zlzxm.studentscreen.ui.activity.manager.ActivityStarter;
import com.zlzxm.studentscreen.ui.activity.manager.BaseActivity;
import com.zlzxm.studentscreen.ui.adapter.TextContentAdapter;
import com.zlzxm.studentscreen.ui.adapter.entity.EntityUnBindDevice;
import com.zlzxm.studentscreen.util.ZViewHelp;
import com.zlzxm.studentscreen.util.deviceinfo.DeviceInfoUtil;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.functions.Consumer;

/**
 * CREATE BY zlzxm ON 2022/3/9
 */
public class AcConfig extends BaseActivity implements View.OnClickListener, OnItemClickListener {

    MyRepository myRepository ;

    RelativeLayout rlServer,rlSeat;

    TextView tvBtnServer,tvBtnBind,tvSeat;


    EditText etService,etDeviceName;

    RecyclerView rvAddress;

    TextContentAdapter textContentAdapter = new TextContentAdapter();

    EntityUnBindDevice selectEntity;

    @Override
    public int loadRootView() {
        ZViewHelp.setStatusBarTransparent(getWindow(),false);
        return R.layout.ac_config;
    }

    @Override
    public void initView() {
        rlServer = ZViewHelp.findById(this,R.id.rlServer);
        rlSeat = ZViewHelp.findById(this,R.id.rlSeat);
        tvBtnServer = ZViewHelp.findById(this,R.id.tvBtnServer);
        tvBtnBind = ZViewHelp.findById(this,R.id.tvBtnBind);
        etService = ZViewHelp.findById(this,R.id.etServer);
        tvSeat = ZViewHelp.findById(this,R.id.tvSeat);
        etDeviceName = ZViewHelp.findById(this,R.id.etDeviceName);
        rvAddress = ZViewHelp.findById(this,R.id.rvAddress);
        rvAddress.setAdapter(textContentAdapter);
        textContentAdapter.setOnItemClickListener(this);
        etService.setText("http://10.0.0.4:8080/");
        showServerEdit();
    }

    @Override
    public void initClickListener() {

        tvBtnServer.setOnClickListener(this);
        tvBtnBind.setOnClickListener(this);
        tvSeat.setOnClickListener(this);

    }

    @Override
    public void initData() {

    }

    @Override
    public void onClick(View view) {
        if(view.getId() == R.id.tvBtnServer){

            String server = etService.getText().toString().trim();

            onClickConnect(server);

        }else if(view.getId() == R.id.tvBtnBind){

            onClickBind();

        }else if(view.getId() == R.id.tvSeat){

            showSeat();

        }else if(view.getId() == R.id.etDeviceName){


        }


    }


    private void onClickConnect(String server){

        RetrofitClient.reSet(server);
        myRepository = new MyRepository();
        MMKV.defaultMMKV().encode(Constant.MMKVkey.SERVER,server);
        myRepository.status(DeviceInfoUtil.getWifiMac(this))
                .compose(RxAndroidHelp.turn())
                .subscribe(new Consumer<BaseResponse<RpDeviceStatus>>() {
                    @Override
                    public void accept(BaseResponse<RpDeviceStatus> baseResponse) throws Exception {

                        if(baseResponse.getCode() == BaseResponse.SUCCEED){

                            if(!baseResponse.getData().isStatus()) {

                                showSeatEdit();

                            }else {

                                bindSucceed(baseResponse.getData().getDeviceInfo().getClassroom(),
                                        baseResponse.getData().getDeviceInfo().getDeviceId(),
                                        baseResponse.getData().getDeviceInfo().getWebsocket(),
                                        baseResponse.getData().getDeviceInfo().getDeviceName());
                            }

                        }else {

                            errorToast(baseResponse.getMsg());
                        }

                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        errorToast("请求出异常了");
                    }
                });



    }


    private void onClickBind(){

        if(selectEntity == null){

            warningToast("请先选择设备位置");

            return;
        }

        String name = etDeviceName.getText().toString();

        if(TextUtils.isEmpty(name)){

            warningToast("请输入设备名称");

            return;
        }

        myRepository.bindDevice(selectEntity.getGroupId(),DeviceInfoUtil.getWifiMac(this),name)
                .compose(RxAndroidHelp.turn())
                .subscribe(new Consumer<BaseResponse<RpBindDevice>>() {
                    @Override
                    public void accept(BaseResponse<RpBindDevice> baseResponse) throws Exception {

                        if(baseResponse.getCode() == 200){


                            bindSucceed(baseResponse.getData().getClassroom(),
                                    baseResponse.getData().getDeviceId(),
                                    baseResponse.getData().getWebsocketUrl(),baseResponse.getData().getDeviceName());
                        }

                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {

                    }
                });




    }

    private void showSeat(){

        myRepository.list()
                .compose(RxAndroidHelp.turn())
                .subscribe(new Consumer<BaseResponse<List<RpUnBindDevice>>>() {
                    @Override
                    public void accept(BaseResponse<List<RpUnBindDevice>> baseResponse) throws Exception {

                        if(baseResponse.getCode() == 200){

                            List<EntityUnBindDevice> list = new ArrayList<>();

                            for (RpUnBindDevice datum : baseResponse.getData()) {

                                EntityUnBindDevice entityUnBindDevice = new EntityUnBindDevice();
                                entityUnBindDevice.setClassroom(datum.getClassroom());
                                entityUnBindDevice.setGroupId(datum.getGroupId());
                                entityUnBindDevice.setGroupName(datum.getGroupName());
                                entityUnBindDevice.setContent(datum.getGroupName());

                                list.add(entityUnBindDevice);
                            }

                            textContentAdapter.setNewInstance(list);
                            rvAddress.setVisibility(View.VISIBLE);

                        }else {
                            errorToast(baseResponse.getMsg());
                        }

                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        errorToast("请求异常了,请重试");
                    }
                });


    }

    private void bindSucceed(String classroom,String deviceId ,String  websocket,String  deviceName){

        MMKV.defaultMMKV().encode(Constant.MMKVkey.NOT_FIRST_OPEN,true);
        MMKV.defaultMMKV().encode(Constant.MMKVkey.CLASSROOM,classroom);
        MMKV.defaultMMKV().encode(Constant.MMKVkey.DEVICE_ID,deviceId);
        MMKV.defaultMMKV().encode(Constant.MMKVkey.WEBSOCKET,websocket);
        MMKV.defaultMMKV().encode(Constant.MMKVkey.DEVICE_NAME,deviceName);

        ServiceStart.startCoreService(AcConfig.this,websocket);

        ActivityStarter.startAcHome(AcConfig.this);

        finish();


    }

    private void showServerEdit(){
        rlServer.setVisibility(View.VISIBLE);
        rlSeat.setVisibility(View.GONE);

    }

    private void showSeatEdit(){
        rlServer.setVisibility(View.GONE);
        rlSeat.setVisibility(View.VISIBLE);

    }


    @Override
    public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        selectEntity = (EntityUnBindDevice) textContentAdapter.getItem(position);
        tvSeat.setText(selectEntity.getGroupName());
        rvAddress.setVisibility(View.GONE);
    }
}
